package org.flexharmony.eclipse.properties.classinclusion;

import java.util.ArrayList;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.flexharmony.eclipse.HarmonyLogger;
import org.flexharmony.eclipse.HarmonyPlugin;

public class JavaSourceContentProvider implements ITreeContentProvider, ILabelProvider
{
  private IFolder rootFolder;

  public JavaSourceContentProvider()
  {}

  public Object[] getElements(Object inputElement)
  {
    rootFolder = (IFolder)inputElement;
    return getChildren(rootFolder);
  }

  public Object[] getChildren(Object parentElement)
  {
    if (parentElement instanceof IFolder)
    {
      try
      {
        IResource[] resources = ((IFolder)parentElement).members();
        ArrayList<Object> elements = new ArrayList<Object>();
        for (IResource resource : resources)
        {
          if (resource instanceof IFolder)
          {
            elements.add(resource);
          }
          else if (resource instanceof IFile)
          {
            if (resource.getName().endsWith(".java"))
            {
              elements.add(resource);
            }
          }
        }
        
        return elements.toArray();
      }
      catch (CoreException cexc)
      {
        HarmonyLogger.logError("Unable to retrieve java source folder children due to core exception.", cexc);
        return new Object[0];
      }
    }
    else
    {
      return new Object[0];      
    }
  }

  public Object getParent(Object element)
  {
    IResource resource = (IResource)element;
    return resource.getParent();
  }

  public boolean hasChildren(Object element)
  {
    return (element instanceof IFolder);
  }

  public void dispose()
  {}

  public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
  {}

  public Image getImage(Object element)
  {
    String imageName = null;
    if (element instanceof IFolder)
    {
      imageName = "package.gif"; 
    }
    else if (element instanceof IFile)
    {
      imageName = "javaSourceFile.gif";
    }
    
    return (imageName == null) ? null : HarmonyPlugin.getImage("icons/" + imageName);
  }

  public String getText(Object element)
  {
    return ((IResource)element).getName();
  }

  public void addListener(ILabelProviderListener listener)
  {}

  public void removeListener(ILabelProviderListener listener)
  {}

  public boolean isLabelProperty(Object element, String property)
  {
    return true;
  }

}
